<?php

namespace app\data\controller\api;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\SDK\ViapiUtils\ViapiUtils;
use app\data\service\AliMessageService;
use think\admin\Controller;
use think\admin\storage\AliossStorage;

/**
 * 阿里云接口
 * Class Data
 * @package app\data\controller\api
 */
class ALiYun extends Controller
{
    /**
     * 行驶证识别
     * @throws ClientException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recognizeDrivingLicense()
    {
        $fileUrl = $this->request->post('url', "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeDrivingLicense/xsz2.jpg");

        $fileUrl = str_replace('https://', 'http://', $fileUrl);

        $accessKeyId = sysconf('storage.alioss_access_key');
        $accessKeySecret = sysconf('storage.alioss_secret_key');
        $fileLoadAddress = ViapiUtils::upload($accessKeyId, $accessKeySecret, $fileUrl);

        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId('cn-shanghai')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('ocr')
                // ->scheme('https') // https | http
                ->version('2019-12-30')
                ->action('RecognizeDrivingLicense')
                ->method('POST')
                ->host('ocr.cn-shanghai.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-shanghai",
                        'Side' => input('side', 'face'),
                        'ImageURL' => $fileLoadAddress,
                    ],
                ])
                ->request();

            $card = $result->toArray();
            if (input('side', 'face') == 'face') {
                $response = [
                    'issue_date' => date('Y-m-d', strtotime($card['Data']['FaceResult']['IssueDate'] ?? '')),
                    'model' => $card['Data']['FaceResult']['Model'] ?? '',
                    'vehicle_type' => $card['Data']['FaceResult']['VehicleType'] ?? '',
                    'owner' => $card['Data']['FaceResult']['Owner'] ?? '',
                    'engine_number' => $card['Data']['FaceResult']['EngineNumber'] ?? '',
                    'plate_number' => $card['Data']['FaceResult']['PlateNumber'] ?? '',
                    'address' => $card['Data']['FaceResult']['Address'] ?? '',
                    'use_character' => $card['Data']['FaceResult']['UseCharacter'] ?? '',
                    'vin' => $card['Data']['FaceResult']['Vin'] ?? '',
                    'register_date' => date('Y-m-d', strtotime($card['Data']['FaceResult']['RegisterDate'] ?? '')),
                ];
            } else {
                $response = [
                    'overall_dimension' => $card['Data']['BackResult']['OverallDimension'] ?? '',
                    'inspection_record' => $card['Data']['BackResult']['InspectionRecord'] ?? '',
                    'unladen_mass' => $card['Data']['BackResult']['UnladenMass'] ?? '',
                    'file_number' => $card['Data']['BackResult']['FileNumber'] ?? '',
                    'traction_mass' => $card['Data']['BackResult']['TractionMass'] ?? '',
                    'gross_mass' => $card['Data']['BackResult']['GrossMass'] ?? '',
                    'plate_number' => $card['Data']['BackResult']['PlateNumber'] ?? '',
                    'approved_passenger_capacity' => $card['Data']['BackResult']['ApprovedPassengerCapacity'] ?? '',
                    'energy_type' => $card['Data']['BackResult']['EnergyType'] ?? '',
                    'approved_load' => $card['Data']['BackResult']['ApprovedLoad'] ?? '',
                ];
            }

            $this->success('行驶证识别成功', $response);
        } catch (ClientException $e) {
            $this->error('您传入的行驶证格式不对 ');
        } catch (ServerException $e) {
            $this->error('你传入的行驶证格式不对 ');
        }
    }

    /**
     * 身份证识别
     * @throws ClientException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recognizeIdentityCard()
    {
        $fileUrl = $this->request->post('url', "https://viapi-oss.oss-cn-shanghai.aliyuncs.com/doc/ocr/shenfz.jpg");

        $accessKeyId = sysconf('storage.alioss_access_key');
        $accessKeySecret = sysconf('storage.alioss_secret_key');
        $fileLoadAddress = ViapiUtils::upload($accessKeyId, $accessKeySecret, $fileUrl);

        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId('cn-shanghai')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('ocr')
                // ->scheme('https') // https | http
                ->version('2019-12-30')
                ->action('RecognizeIdentityCard')
                ->method('POST')
                ->host('ocr.cn-shanghai.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-shanghai",
                        'Side' => "face",
                        'ImageURL' => $fileLoadAddress,
                    ],
                ])
                ->request();

            $card = $result->toArray();
            $response = [
                'Address' => $card['Data']['FrontResult']['Address'] ?? '',
                'Gender' => $card['Data']['FrontResult']['Gender'] ?? '',
                'Nationality' => $card['Data']['FrontResult']['Nationality'] ?? '',
                'BirthDate' => $card['Data']['FrontResult']['BirthDate'] ?? '',
                'Name' => $card['Data']['FrontResult']['Name'] ?? '',
                'IDNumber' => $card['Data']['FrontResult']['IDNumber'] ?? '',
            ];
            $this->success('身份证识别成功', $response);
        } catch (ClientException $e) {
            $this->error($e->getErrorMessage());
        } catch (ServerException $e) {
            $this->error($e->getErrorMessage());
        }
    }

    /**
     * 银行卡识别
     * @throws ClientException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recognizeBankCard()
    {
        $fileUrl = $this->request->post('url', "http://cattle666.cn-beijing.oss.aliyuncs.com/d4/a422e5cb11ce9df912d65f324e0666.jpg");
        $accessKeyId = sysconf('storage.alioss_access_key');
        $accessKeySecret = sysconf('storage.alioss_secret_key');
        $fileLoadAddress = ViapiUtils::upload($accessKeyId, $accessKeySecret, $fileUrl);

        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId('cn-shanghai')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('ocr')
                // ->scheme('https') // https | http
                ->version('2019-12-30')
                ->action('RecognizeBankCard')
                ->method('POST')
                ->host('ocr.cn-shanghai.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-shanghai",
                        'ImageURL' => $fileLoadAddress,
                    ],
                ])
                ->request();

            $card = $result->toArray();
            $response = [
                'bank_card_number' => $card['Data']['CardNumber'] ?? '',
                'bank_name' => $card['Data']['BankName'] ?? '',
                'bank_valid_date' => $card['Data']['ValidDate'] ?? '',
            ];
            $this->success('身份证识别成功', $response);
        } catch (ClientException $e) {
            $this->error($e->getErrorMessage());
        } catch (ServerException $e) {
            $this->error($e->getErrorMessage());
        }
    }

    /**
     * 银行卡信息校验
     */
    public function checkBank()
    {
        $data = $this->_vali([
            'bank_card_number.require' => '请输入银行卡信息',
            'id_card.require' => '请输入身份证信息',
            'phone.require' => '请输入手机号码',
            'name.require' => '请输入真实姓名',
            'verify.require' => '验证码不能为空',
            'phone.mobile' => '手机号码格式错误！',
        ]);

        if (!AliMessageService::instance()->checkVerifyCode($data['verify'], $data['phone'], 'band_bank')) {
            $this->error('短信验证失败！');
        }

        error_reporting(E_ALL || ~E_NOTICE);
        $host = "https://b4bankcard.market.alicloudapi.com";
        $path = "/bankCheck4New";
        $method = "GET";
        $appcode = "1abc7a53a7d147ffbe680b9fdcd5ba06";//开通服务后 买家中心-查看AppCode
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "idCard={$data['id_card']}&accountNo={$data['bank_card_number']}&mobile={$data['phone']}&name=".urlencode($data['name']);

        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $out_put = curl_exec($curl);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);
        if ($httpCode == 200) {
            $body = json_decode($body, true);
            if ($body['status'] == '01') {
                $this->success('匹配成功！', $body);
            } else {
                $this->error($body['msg'], $body);
            }
        } else {
            if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
                $this->error('参数错误！');
            } elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
                $this->error('AppCode错误');
            } elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
                $this->error('请求的 Method、Path 或者环境错误');
            } elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
                $this->error('服务未被授权（或URL和Path不正确）');
            } elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
                $this->error('套餐包次数用完');
            } elseif ($httpCode == 500) {
                $this->error('API网关错误');
            } elseif ($httpCode == 0) {
                $this->error('URL错误');
            } else {
                $this->error('参数名错误 或 其他错误');
                $headers = explode("\r\n", $header);
                $headList = array();
                foreach ($headers as $head) {
                    $value = explode(':', $head);
                    $headList[$value[0]] = $value[1];
                }
                print($headList['x-ca-error-message']);
            }
        }
    }

    /**
     * 物流查询
     */
    public function trace()
    {
        $data = $this->_vali([
            'send_number.require' => '请输入物流单号',
            'company_code.require' => '请输入物流类型',
        ]);

        error_reporting(E_ALL || ~E_NOTICE);
        $host = "https://wdexpress.market.alicloudapi.com";
        $path = "/gxali";
        $method = "GET";
        $appcode = "1abc7a53a7d147ffbe680b9fdcd5ba06";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "n={$data['send_number']}&t={$data['company_code']}";

        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);

        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $out_put = curl_exec($curl);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);
        if ($httpCode == 200) {
            $this->success('匹配成功！', json_decode($body, true));
        } else {
            if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
                $this->error('参数错误！');
            } elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
                $this->error('AppCode错误');
            } elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
                $this->error('请求的 Method、Path 或者环境错误');
            } elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
                $this->error('服务未被授权（或URL和Path不正确）');
            } elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
                $this->error('套餐包次数用完');
            } elseif ($httpCode == 500) {
                $this->error('API网关错误');
            } elseif ($httpCode == 0) {
                $this->error('URL错误');
            } else {
                $this->error('参数名错误 或 其他错误');
                $headers = explode("\r\n", $header);
                $headList = array();
                foreach ($headers as $head) {
                    $value = explode(':', $head);
                    $headList[$value[0]] = $value[1];
                }
                print($headList['x-ca-error-message']);
            }
        }
    }
}